﻿using System;
using System.Net.Sockets;

namespace CCSSolderUI.Models
{
    public static class SHIJIEScanner
    {
        public static string Connect(string server, int port, string message,bool isreceive)
        {
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer
                // connected to the same address as specified by the server, port
                // combination.
                TcpClient client = new TcpClient(server, port);
                client.SendTimeout = 2000;
                client.ReceiveTimeout = 2000;

                // Translate the passed message into ASCII and store it as a Byte array.
                byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer.
                stream.Write(data, 0, data.Length);
                if (isreceive)
                {
                    // Receive the TcpServer.response.

                    // Buffer to store the response bytes.
                    data = new byte[256];

                    // String to store the response ASCII representation.
                    string responseData = string.Empty;

                    // Read the first batch of the TcpServer response bytes.
                    int bytes = stream.Read(data, 0, data.Length);
                    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                    // Close everything.
                    stream.Close();
                    client.Close();
                    return responseData;
                }
                else
                {
                    // Close everything.
                    stream.Close();
                    client.Close();
                    return null;
                }
            }
            catch (Exception ex)
            {             
                return "Error";
            }
        }
    }
}
